package com.chs.recoginition.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取spring容器，以访问容器中定义的其他bean
 */
@Slf4j
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name) {
        T bean = null;
        try {
            bean = (T) applicationContext.getBean(name);
        } catch (Exception ignored) {
        }
        return bean;
    }

    public static <T> T getBean(Class<T> clazz) {
        T bean = null;
        try {
            bean = applicationContext.getBean(clazz);
        } catch (Exception ignored) {
        }
        return bean;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
